package util;

import model.SimpleGoL;

import java.io.*;

/**
 * @author Xu,
 * @data 2020/11/11，
 * @time 12:37
 */
public class Utils {
    public static SimpleGoL initMapFromFile(String path){
        int size;
        int day;
        System.out.println(path);
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
            StringBuffer stringBuffer;
            String line = reader.readLine();
            String[] array = line.split(" ");
            size = Integer.parseInt(array[0]);
            System.out.println(size);
            String line1 = reader.readLine();
            String[] array1 = line1.split(" ");
            day = Integer.parseInt(array1[0]);
            System.out.println(day);
            /**
             * 读取文件的存活细胞，将map对应位置置1，否则置0；
             * reader.readLine() != null，否则读取停止不下来导致报错NPE；
             *
             * 读取数据的string尽量换成stringbuffer，性能更佳
             */
            int[][] map = new int[size][size];
            for(int i=0; i<size; i++){
                for(int j=0; j<size; j++){
                    map[i][j] = 0;
                }
            }

            String value = reader.readLine();
            while(value != null){
                boolean flag = false;
                String[] array2 = value.split(",");
                for(int i=0; i<size; i++){
                    if(i == Integer.parseInt(array2[0])){
                        for (int j=0; j<size; j++){
                            if (j == Integer.parseInt(array2[1])){
                                map[i][j] = 1;
                                System.out.println(array2[0] + " " + array2[1]);
                                flag = true;
                                break;
                            }
                        }
                    }
                    if(flag){
                        value = reader.readLine();
                        break;
                    }
                }
            } 
            
            SimpleGoL simpleGoL = new SimpleGoL(size, day, map);
            return simpleGoL;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(reader != null){
                try{
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return  null;
    }

}
